package model.led.sequential;

import framework.common.DeviceRequest;
import framework.common.DeviceResponse;
import framework.common.SensorRequest;
import framework.common.SensorResponse;
import framework.sequential.Client;

public class OnOffClient extends Client {
	public String term;

	public OnOffClient(String user, String term) {
		super(user);
		this.term = term;
	}

	public boolean isOn() {
		DeviceRequest req = new DeviceRequest(this);
		req.add(new SensorRequest(SensorRequest.GET, term, Integer.valueOf(1)));
		DeviceResponse res = request(req);
		for (SensorResponse s : res.getResponses()) {
			String attr = s.getAttribute();
			if (attr.equals(term)) {
				Object val = s.getValue();
				if (val instanceof Integer) {
//					System.out.println("isOn=" + val);
					return (((Integer) val).intValue() == 1);
				} else
					throw new RuntimeException("Illegal type: " + term);
			}
		}
		throw new RuntimeException("no such attribute: " + term);
	}

	public boolean isOff() {
		return !isOn();
	}

	public void turnOn() {
		DeviceRequest req = new DeviceRequest(this);
		req.add(new SensorRequest(SensorRequest.SET, term, Integer.valueOf(1)));
		DeviceResponse res = request(req);
		System.out.println(res);
	}

	public void turnOff() {
		DeviceRequest req = new DeviceRequest(this);
		req.add(new SensorRequest(SensorRequest.SET, term, Integer.valueOf(0)));
		DeviceResponse res = request(req);
		System.out.println(res);
	}

}
